package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {


    /**
     * 全局过滤器业务
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        获取响应对象
        ServerHttpResponse response = exchange.getResponse();
//        获取请求对象
        ServerHttpRequest request = exchange.getRequest();
//        获取请求路径
        String path = request.getURI().getPath();
        log.info("path={}",path);
//        /admin/login/in
//        判断是否登录请求
        if(path.contains("/login/in")){
//        如果是登录，放行
            log.info("是登录请求，直接放行");
            return chain.filter(exchange);
        }
//        如果不是登录请求，从请求头获取token
        String token = request.getHeaders().getFirst("token");
//        如果没有token，返回401,结束当前请求
        if(StringUtils.isBlank(token)){
            log.error("token为空，401 直接返回");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        如果有token，解析token
        try {
            Payload payload = JwtUtils.getInfoFromToken(token);
//            获取userid
            Integer userId = payload.getUserId();
            log.info("userid=={}",userId);
//            把userId 放入转发的请求头中，后面的微服务就不需要在解析token
//            生成一个新的ServerHttpRequest
            ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId.toString());
            }).build();
//            把exchange中的request改变
            exchange.mutate().request(httpRequest).build();
        }catch (Exception e){
            log.error("token无效，返回401");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        log.info("全局过滤器验证jwt，通过，放行");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
